package com.smartpi.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import com.smartpi.pojo.Common;

/**
 * Servlet implementation class ControlLightServlet
 */
public class ControlCurtainServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ControlCurtainServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String command = request.getParameter(Common.CURTAIN_PARAMETER);
		PrintWriter out = response.getWriter();
		ServletContext ctx = this.getServletContext();
		String actionCode = (String) ctx.getAttribute(Common.CURTAIN_PARAMETER);
		JSONObject info = new JSONObject();
		if (actionCode == null) {
			ctx.setAttribute(Common.CURTAIN_PARAMETER, command);
			if ("0".equals(command)) {
				// first close
				Runtime.getRuntime().exec(Common.COMMAND_OPEN_CURTAIN);
				info.put("info", "close curtain");

			} else if ("1".equals(command)) {
				// first open
				Runtime.getRuntime().exec(Common.COMMAND_CLOSE_CURTAIN);
				info.put("info", "open curtain");
			} else {
				info.put("info", "error");
			}
		} else if (actionCode.equals(command)) {
			// nothind to do
			info.put("info", "already");
		} else if (!actionCode.equals(command) && "0".equals(command)) {
			// close
			Runtime.getRuntime().exec(Common.COMMAND_OPEN_CURTAIN);
			ctx.setAttribute(Common.CURTAIN_PARAMETER, command);
			info.put("info", "close curtain");

		} else if (!actionCode.equals(command) && "1".equals(command)) {
			// open
			Runtime.getRuntime().exec(Common.COMMAND_CLOSE_CURTAIN);
			ctx.setAttribute(Common.CURTAIN_PARAMETER, command);
			info.put("info", "open curtain");
		}
		out.println(info.toString());
		out.close();

	}
}
